package com.doudizu.shoesonline.controller;

import com.doudizu.shoesonline.common.BaseResponse;
import com.doudizu.shoesonline.common.ResultUtils;
import com.doudizu.shoesonline.constant.CartConstant;
import com.doudizu.shoesonline.model.entity.Cart;
import com.doudizu.shoesonline.model.vo.CartDetailVO;
import com.doudizu.shoesonline.service.CartService;
import com.doudizu.shoesonline.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author ln
 */
@RestController
@RequestMapping("/cart")
@Api(tags = "购物车模块")
public class CartController {

    @Resource
    private CartService cartService;

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;


    @GetMapping("/list")
    @ApiOperation("获取购物车清单")
    public BaseResponse list() {
        List<CartDetailVO> cartList = cartService.getCart();
        return ResultUtils.success(cartList);
    }

    @PostMapping("/ids")
    @ApiOperation("根据ids获取购物车内容")
    public BaseResponse ids(@RequestBody List<Integer> ids) {
        List<CartDetailVO> cartList = cartService.getCartByIds(ids);
        return ResultUtils.success(cartList);
    }

    @PostMapping("/add")
    @ApiOperation("添加到购物车")
    public BaseResponse add(@RequestBody Cart cart) {
        cart.setUserId(userService.getLoginUser().getId());
        cartService.save(cart);
        String key = CartConstant.CART_PRODUCT_LIST +userService.getLoginUser().getId();
        redisTemplate.delete(key);
        return ResultUtils.success(cart);
    }

    @PostMapping("/delete")
    @ApiOperation("删除购物车")
    public BaseResponse delete(@RequestBody List<Integer> ids) {
        cartService.removeBatchByIds(ids);
        String key = CartConstant.CART_PRODUCT_LIST +userService.getLoginUser().getId();
        redisTemplate.delete(key);
        return ResultUtils.success(null);
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改购物车",notes = "传id和修改后数量")
    public BaseResponse update(@RequestBody Cart cart) {
        if (cart.getNum() > 0) {
            cartService.updateById(cart);
        }
        if (cart.getNum() <=0) {
            cartService.removeById(cart.getId());
        }
        String key = CartConstant.CART_PRODUCT_LIST +userService.getLoginUser().getId();
        redisTemplate.delete(key);
        return ResultUtils.success(null);
    }
}
